//
//  MyNoteBookViewController.m
//  MansApp
//
//  Created by lanou3g on 15/7/23.
//  Copyright (c) 2015年 ACH. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "MyNoteBookViewController.h"
#import "MyNoteBookView.h"
#import "KeyboardInputAccessoryView.h"
#import "NoteTapeView.h"
#import "InfoTextAttachment.h"
#import "CarPicViewController.h"
#import "MyNoteSingleton.h"
@interface MyNoteBookViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,AVAudioRecorderDelegate,UITextFieldDelegate>

@property(nonatomic ,copy)NSString *diaryDate;
@property(nonatomic,strong)MyNoteBookView *noteBook;
@property(nonatomic,assign)BOOL isWrite;
@property(nonatomic,assign)BOOL isFont;
@property(nonatomic,assign)BOOL isBackgroundPic;
@property(nonatomic,strong)NSMutableArray *tableArray;
@property(nonatomic,assign)CGRect keyboardRect;
@property(nonatomic,strong)NoteTapeView *tapeView;
@property(nonatomic,assign)BOOL isTape;
@property(nonatomic,assign)BOOL isResponderForTape;
@property(nonatomic,strong)AVAudioRecorder *recorder;
@property(nonatomic,copy)NSString *recorderInfo;
@property(nonatomic,strong)AVAudioPlayer *myPlayer;
@property(nonatomic,assign)BOOL isDeleteText;
// 每次录音有变动 会刷新 录音 info 信息
@property(nonatomic,strong)NSMutableSet *tapeSet;

// 保存所有的 录音信息  根据-(BOOL)isTapeBeing; 进行更正 并 删除多余录音
@property(nonatomic,strong)NSMutableSet *myTapeSet;


@property(nonatomic,strong)NSMutableArray *themeArray;

@property(nonatomic,copy)NSString *motif;
@property(nonatomic,assign)BOOL isMotif;

@property(nonatomic,assign)BOOL isChange;


@end

@implementation MyNoteBookViewController

- (void)loadView{

    self.noteBook = [[MyNoteBookView alloc]init];
    self.view = self.noteBook;
    [self.noteBook.controlView addTarget:self action:@selector(controlViewAction:) forControlEvents:UIControlEventTouchUpInside];

    
    KeyboardInputAccessoryView *key = [[KeyboardInputAccessoryView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kP6Height(40))];
    [key addTarget:self action:@selector(keyBoardAction:) forControlEvents:UIControlEventTouchUpInside];
     self.noteBook.myTextView.inputAccessoryView = key;
    [self.noteBook.fontControl addTarget:self action:@selector(fontControlAction:) forControlEvents:UIControlEventTouchUpInside];
    self.noteBook.myTextView.delegate = self;
    self.noteBook.myTextField.delegate = self;
    [self settingNoteTableView];
    
  // 设置了 UITextView 中的 layoutManager(NSLayoutManager) 的是否非连续布局属性，默认是 YES，设置为 NO 后 UITextView 就不会再自己重置滑动了。
    self.noteBook.myTextView.layoutManager.allowsNonContiguousLayout = NO;
     self.recorder.delegate = self;
    
    if (self.diaryModel != nil) {
        self.noteBook.myTextView.attributedText = self.diaryModel.diary;
        self.noteBook.myTextField.text = self.diaryModel.diaryName;
        [self  SetTheme:self.diaryModel.motif];
        if (_isMotif) {
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readWrite"] forState:UIControlStateNormal];
        }else
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readBlack"] forState:UIControlStateNormal];
        
    }
    
    
    __block MyNoteBookViewController *kSelf = self;
    [MyNoteSingleton shareInstance].singletonBlock = ^(){
        
        
        [kSelf saveDiary];
           };
    
    
}

- (void)saveDiary{
    
    
    if (self.diaryModel) {
        
        if (self.noteBook.myTextView.attributedText.length != 0 || self.noteBook.myTextField.text.length != 0) {
           NSString *myDate =  [self baseSaveWhatTime:1];

            if (self.motif != nil) {
              [[ACHdb sharedInstance] updataWithDate:myDate upMotif:self.motif];
            }
        }
        else{
            NSLog(@"删除");
            [[ACHdb sharedInstance] deleteWithDate:self.diaryModel.date];
        }
        
 
    }
    else{
        if (self.noteBook.myTextView.attributedText.length != 0 || self.noteBook.myTextField.text.length != 0) {
            
            NSString *myDate = [self baseSaveWhatTime:0];
            
            if (_motif) {
                
                [[ACHdb sharedInstance] updataWithDate:myDate upMotif:self.motif];
            }else{
                [[ACHdb sharedInstance] updataWithDate:myDate upMotif:@"5"];
            }


        }
        
    }
    
    
}

- (NSString *)baseSaveWhatTime:(int )time{
    NSString *myDate;
    if (time == 1) {
        myDate  = [self whatIsTime];
        [[ACHdb sharedInstance] updataWithDate:self.diaryModel.date upNewDate:myDate];
    }
    else{
        
        myDate  = self.diaryDate;
    }
    
    __block NSMutableString *str = [NSMutableString string];
    __block NSMutableArray *picArray = [NSMutableArray array];
    [self.noteBook.myTextView.attributedText enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.noteBook.myTextView.attributedText.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSTextAttachment *value, NSRange range, BOOL *stop) {
        
        if (value && [value isKindOfClass:[InfoTextAttachment class]]) {
            
            [str appendFormat:@"%@/",((InfoTextAttachment *)value).infoString];
        }
        else if(value && [value isKindOfClass:[NSTextAttachment class]]){
            
            NSData *data = UIImageJPEGRepresentation(value.image, 0.5);
            
            [picArray addObject:data];
        }
    }
     ];
    [[ACHdb sharedInstance] upDatawithDate:myDate  wtihDiary:self.noteBook.myTextView.attributedText diaryName:self.noteBook.myTextField.text tape:str picArray:picArray];
    
    return myDate;
}

#pragma mark - 当前时间
- (NSString *)whatIsTime{
    
     NSDateFormatter *forMatter = [[NSDateFormatter alloc]init];
    [forMatter  setDateFormat:@"yyyyMMddHHmmss"];
    
     return  [forMatter  stringFromDate:[NSDate date]];
    
}


#pragma mark -  textView 的 代理方法


-(NSMutableSet *)tapeSet{
    if (!_tapeSet) {
        _tapeSet = [NSMutableSet set];
    }
    
    return _tapeSet;
}

- (NSMutableSet *)myTapeSet{
    if (!_myTapeSet) {
        _myTapeSet = [NSMutableSet set];
    }
    
    return _myTapeSet;
    
}

-(BOOL)isTapeBeing{
    
      if (self.myTapeSet.count == 0) {
        return NO;
    }
      else{
    __block MyNoteBookViewController *kSelf = self;
    [self.tapeSet removeAllObjects];
    [self.noteBook.myTextView.attributedText enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.noteBook.myTextView.attributedText.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSTextAttachment *value, NSRange range, BOOL *stop) {
        if (value && [value isKindOfClass:[InfoTextAttachment class]]){
            
            [kSelf.tapeSet addObject:((InfoTextAttachment *)value).infoString];
         
        }
    }];
    
       [self.myTapeSet minusSet:self.tapeSet];
          
        NSFileManager *manager = [NSFileManager defaultManager];
        
        if( [manager  fileExistsAtPath:[self byAppendingForCache:self.myTapeSet.anyObject]]){
          
            [manager removeItemAtPath:[self byAppendingForCache:self.myTapeSet.anyObject] error:nil];
        };
    
         [self.myTapeSet setSet:self.tapeSet];
    
          return YES;
      }
}


    


- (NSString *)byAppendingForCache:(NSString *)str{
    
  NSString *myCachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    return [NSString stringWithFormat:@"%@/%@",myCachePath,str];
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
 
    if (_isDeleteText) {
        _isDeleteText = NO;
        [self  isTapeBeing];
        
    }
       

  
}
- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"更改完");
    _isChange = YES;
    
    CGRect line = [textView caretRectForPosition:
                   textView.selectedTextRange.start];
    CGFloat overflow = line.origin.y + line.size.height
    - ( textView.contentOffset.y + textView.bounds.size.height
       - textView.contentInset.bottom - textView.contentInset.top );
    if ( overflow > 0 ) {
        // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
        // Scroll caret to visible area
        CGPoint offset = textView.contentOffset;
        offset.y += overflow + 7; // leave 7 pixels margin
        // Cannot animate with setContentOffset:animated: or caret will not appear
        [UIView animateWithDuration:.2 animations:^{
            [textView setContentOffset:offset];
        }];
    }
    

    
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if (text.length == 0) {
        _isDeleteText = YES;
    }

    

     return YES;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange{
    if ([textAttachment isKindOfClass:[InfoTextAttachment class]] ) {
        
//        NSLog(@"我进来了");
        AVAudioSession *avSession = [AVAudioSession sharedInstance];
        [avSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        
        
        
        [avSession setActive:YES  error:nil];
        
//        NSLog(@"%@",((InfoTextAttachment*)textAttachment).infoString);
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        NSString *allPath = [NSString stringWithFormat:@"%@/%@",path,((InfoTextAttachment*)textAttachment).infoString];
        self.myPlayer = nil;
        self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath: allPath] error:nil];
        [self.myPlayer prepareToPlay];
        [self.myPlayer play];
    }
    else{
        CarPicViewController *carPic = [[CarPicViewController alloc]init];
        NSMutableArray  *picArray = [NSMutableArray array];
        __block NSMutableArray  *arr = picArray;
       [self.noteBook.myTextView.attributedText enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.noteBook.myTextView.attributedText.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSTextAttachment *value, NSRange range, BOOL *stop) {
           
           if (value && ![value isKindOfClass:[InfoTextAttachment class]]) {
               [arr addObject:value.image];
               
           }
           
           
       }
        ];
        if (picArray.count == 1) {
            
            [picArray addObject:[UIImage imageNamed:@"touming"]];
        }
        carPic.picArray = picArray;
        [self presentViewController:carPic animated:NO completion:nil];
        
        
 
    }
 
    
    return YES;
}


- (NSString *)diaryDate{
    if (!_diaryDate) {
        _diaryDate =[self whatIsTime];
     [[ACHdb sharedInstance] insertDate:_diaryDate];
    }
    
    return _diaryDate;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    return [textField resignFirstResponder];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSLog(@"更改标题");
    _isChange = YES;
    return YES;
}
#pragma mark - 调整字体大小;

-(void)fontControlAction:(UIButton *)sender{
    
    switch (sender.tag) {
        case 100:{
            self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:14];
            [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"NoteBookFont"];
            
            
        }
            break;
        case 101:{
              self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:17];
            [[NSUserDefaults standardUserDefaults] setObject:@2 forKey:@"NoteBookFont"];
        }
            break;
        case 102:{
            self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:20];
            [[NSUserDefaults standardUserDefaults] setObject:@3 forKey:@"NoteBookFont"];
        }
            break;
        default:
            break;
    }
    
    
}

-(void)setFont{
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"NoteBookFont"]) {
       self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:17];
    }
    else{
    int a = [[[NSUserDefaults standardUserDefaults]objectForKey:@"NoteBookFont"] intValue];
    switch (a) {
        case 1:
            self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:14];
            break;
            case 2:
            self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:17];
            break;
        default:
            self.noteBook.myTextView.font  = [UIFont fontWithName:@"Georgia-Italic" size:20];
            break;
    }
    }
}

#pragma mark -  辅助键盘的 button  触发方法;

-(NoteTapeView *)tapeView{
    if (!_tapeView) {
  _tapeView = [[NoteTapeView alloc]initWithFrame:CGRectMake(self.keyboardRect.origin.x, self.keyboardRect.origin.y + 40, kWidth, self.keyboardRect.size.height - 40)];
        
        [_tapeView.button addTarget:self action:@selector(tapeViewButtonUpInsideAction) forControlEvents:UIControlEventTouchUpInside];
        [_tapeView.button addTarget:self action:@selector(tapeViewButtonDownAction) forControlEvents:UIControlEventTouchDown];
        
    }
    
    return _tapeView;
}

#pragma mark - 录音方法

- (void)tapeIsComming{
 
    AVAudioSession *avSession = [AVAudioSession sharedInstance];
    [avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [avSession setActive:YES  error:nil];
    
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:44100.0],AVSampleRateKey,[NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,@2,AVNumberOfChannelsKey, nil];
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    self.recorderInfo = nil;
    self.recorderInfo = [NSString stringWithFormat:@"%@.aac",[self whatIsTime]];
    NSLog(@"%@",self.recorderInfo);
  NSString *allPath = [NSString stringWithFormat:@"%@/%@",path,_recorderInfo];
    self.recorder = nil;
    self.recorder = [[AVAudioRecorder alloc]initWithURL:[NSURL fileURLWithPath:allPath]settings:settings error:nil];
    NSLog(@"%@",allPath);
    [self.recorder record];
    self.recorder.meteringEnabled = YES;
   
    
}



-(void)tapeViewButtonUpInsideAction{
    NSLog(@"录音");
    _isChange = YES;
    [self.tapeView animationStop];
    
    InfoTextAttachment *ment = [InfoTextAttachment new];
    ment.image = [UIImage imageNamed:@"shengbo"];
    ment.infoString = self.recorderInfo;
    ment.bounds = CGRectMake(0, 0,kP6width(300), kP6Height(30));
    [self.noteBook.myTextView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:ment] atIndex:self.noteBook.myTextView.selectedRange.location];

    
    [self.recorder stop];
    [self.myTapeSet addObject:self.recorderInfo];
//    NSLog(@"self.myTapeSet.count %ld",self.myTapeSet.count);

    [self setFont];
}

-(void)tapeViewButtonDownAction{
    
    [self.tapeView animationStart];
    [self tapeIsComming];
    
    
}



- (void)keyBoardAction:(UIButton *)sender{
    switch (sender.tag) {
        case 100:{
            
            _isTape = !_isTape;
            if (_isTape) {
                
            
         self.noteBook.myTextView.inputView = self.tapeView;
   
            }
            else{
                
                self.noteBook.myTextView.inputView = nil;
            }
            _isResponderForTape = YES;
            [self.noteBook.myTextView resignFirstResponder];
            [self.noteBook.myTextView becomeFirstResponder];
             _isResponderForTape = NO;
           
        }
            break;
        case 101:{
            [self openCameraOrPhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        }
            break;
        case 102:{
      [self openCameraOrPhotoLibrary:UIImagePickerControllerSourceTypeCamera];
            
            
        }
            break;
        default:{
            
            [self.noteBook.myTextView resignFirstResponder];
            self.noteBook.myTextView.inputView = nil;
        }
            break;
    }
    
    
    
    
}

- (void)temAction{
    
}

//- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
//    if (action == @selector(copy:))
//        return YES;
////    else if (action == @selector(paste:))
////        return YES;
////    else if (action == @selector(select:))
////        return YES;
////    else if (action == @selector(selectAll:))
////        return YES;
//    else if (action == @selector(toggleBoldface:))
//        return YES;
//    else if (action == @selector(toggleItalics:))
//        return YES;
//    else if (action == @selector(toggleUnderline:))
//        return YES;
//    else if (action == @selector(increaseSize:))
//        return YES;
//    else if (action == @selector(decreaseSize:))
//        return YES;
//    else return NO;
//}
- (void)controlViewAction:(UIButton *)sender{
    switch (sender.tag) {
        case 100:{
            BOOL changeB = NO;
            
            
            if (self.noteBook.myTextView.attributedText.length != 0 || self.noteBook.myTextField.text.length != 0) {
                
                if (_isChange) {
                    
                    NSLog(@"123");
                    [MBProgressHUD   showMessage:@"保存中..."];
                    changeB = YES;
                }
            }
            
            __block  MyNoteBookViewController *kSelf = self;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                NSLog(@"1所在线程 ==== %d",[NSThread isMainThread]);
                if (_isChange) {
                    
                    [kSelf saveDiary];
                }
                
                
                // 回克
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSLog(@"2所在线程 =======%d",[NSThread isMainThread]);
                    if (changeB) {
                        
                        if (_isChange) {
                            
                            
                            [MBProgressHUD hideHUD];
                            [MBProgressHUD showError:@"保存成功"];
                            if ([MyNoteSingleton shareInstance].reloadBlcok) {
                                [MyNoteSingleton shareInstance].reloadBlcok();
                            }
                            
                        }
                        
                    }
                    
                   
                });
                
                
            });
            
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
            
            
        }
            break;
        case 101:{
            
            CGRect rect = self.noteBook.fontControl.frame;
            _isFont = !_isFont;
            _isFont == YES ? (self.noteBook.fontControl.frame = CGRectMake(kP6width(30), rect.origin.y, rect.size.width, rect.size.height)) :(self.noteBook.fontControl.frame = CGRectMake(-300, rect.origin.y, rect.size.width, rect.size.height)) ;

            
        }
            break;
        case 102:{
            _isWrite = !_isWrite;
            if (_isWrite) {
                self.noteBook.myTextView.editable =  NO;
                
                if (_isMotif) {
                 [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"editWrite"] forState:UIControlStateNormal];
                }else
                [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"editBlack"] forState:UIControlStateNormal];
                
                
                
            }
            else {
                self.noteBook.myTextView.editable = YES;
                if (_isMotif) {
                   [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readWrite"] forState:UIControlStateNormal];
                }else
             [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readBlack"] forState:UIControlStateNormal];
                
        
            }
        }
            break;
        default:{
            _isBackgroundPic = !_isBackgroundPic;
            
            CGRect rect = self.noteBook.tableView.frame;
            _isBackgroundPic == YES ? (self.noteBook.tableView.frame = CGRectMake(rect.origin.x, kHeight- kP6Height(170), rect.size.width, rect.size.height)) :(self.noteBook.tableView.frame = CGRectMake(rect.origin.x,1500, rect.size.width, rect.size.height));
            
            
        }
            break;
    }
    
    
    
    
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    NSLog(@"更改图像");
    _isChange = YES;
    NSTextAttachment *ment = [NSTextAttachment new];
    ment.image =image;
    CGSize size = image.size;
   
    ment.bounds = CGRectMake(0, 0, kP6width(80), kP6Height(80) * size.height/ size.width );
    [self.noteBook.myTextView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:ment] atIndex:self.noteBook.myTextView.selectedRange.location];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self setFont];
    [self.noteBook.myTextView becomeFirstResponder];
}
#pragma mark - 开启相机/相册

- (void)openCameraOrPhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    
    UIImagePickerController *imagepicker=[[UIImagePickerController alloc]init];
    imagepicker.delegate=self;
    imagepicker.allowsEditing=NO;
    imagepicker.sourceType=type;
    
    [self presentViewController:imagepicker animated:YES completion:nil];
    imagepicker = nil;
    
    
    
    
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    
}

#pragma mark - 选择背景图的 tableView;
-(NSMutableArray *)themeArray{
    if (!_themeArray ) {
        _themeArray = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"backgroundRed"],[UIImage imageNamed:@"backgroundGreen"],[UIImage imageNamed:@"backgroundPink"],[UIImage imageNamed:@"backgroundGril"],[UIImage imageNamed:@"backgroundBlackboard"],[UIImage imageNamed:@"318769-130G60R61724"],nil];
    }
    
    return _themeArray;
}

- (void)settingNoteTableView{
    self.tableArray = [NSMutableArray array];
    NSMutableArray *array1 = @[@"孜孜不倦",@"春的希望",@"秋的收获",@"伞和女人",@"斯坦福",@"羊皮纸"].mutableCopy;
    [self.tableArray addObject:self.themeArray];
    [self.tableArray addObject:array1];
    [self.noteBook settingTableView:self];
    self.noteBook.tableView.backgroundColor = [UIColor clearColor];
    
    
    
}
- (void)SetTheme:(NSString *)string{
    int a = [string intValue];
    
    self.noteBook.imageView.image = [self.tableArray.firstObject objectAtIndex:a];
  _isMotif = [self.noteBook settingColor:a];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kP6Height(50);
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.tableArray.firstObject count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    cell.backgroundColor = [UIColor clearColor];

    UIImageView *imageView =[[UIImageView alloc]initWithImage:[self.tableArray.firstObject objectAtIndex:indexPath.row]];
    imageView.frame = CGRectMake(0, 0, kP6Height(40), kP6Height(40));
    cell.textLabel.textColor =[UIColor whiteColor];
    cell.accessoryView =imageView;
    cell.textLabel.text = [self.tableArray.lastObject objectAtIndex:indexPath.row];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"更改主题");
    _isChange = YES;
    self.noteBook.imageView.image = [self.tableArray.firstObject objectAtIndex:indexPath.row];
    self.motif = [NSString stringWithFormat:@"%ld",indexPath.row];
    
  _isMotif = [self.noteBook settingColor:indexPath.row];
    if (_isWrite) {

        if (_isMotif) {
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"editWrite"] forState:UIControlStateNormal];
        }else
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"editBlack"] forState:UIControlStateNormal];
        
        
        
    }
    else {
        if (_isMotif) {
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readWrite"] forState:UIControlStateNormal];
        }else
            [self.noteBook.controlView.writeOrRead setBackgroundImage:[UIImage imageNamed:@"readBlack"] forState:UIControlStateNormal];
        
        
    }
    
    
}


#pragma mark - 监听键盘
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setFont];
    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
 
    // 监听键盘收回
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil];
    
}
#pragma mark - 键盘弹起时触发的方法
- (void)keyboardDidShow:(NSNotification *)notification
{
    // 当键盘弹出的时候
    // 实际应用开发中 一般是将textField放在一个View上  当键盘弹起的时候 修改View的布局 (frame)
    // 获取键盘弹起的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    // 当键盘弹起时候 修改View的frame 让View整体上移
    
    self.keyboardRect = keyboardRect;
    
    
    if (_isWrite){
        self.noteBook.myTextView.inputAccessoryView.hidden = YES;
        [self.noteBook myTextViewHeight:-1];
    }
    else {
      self.noteBook.myTextView.inputAccessoryView.hidden = NO;
        if (!_isResponderForTape) {
            [self.noteBook myTextViewHeight:keyboardRect.size.height];
        CGRect rect = self.noteBook.fontControl.frame;
    self.noteBook.fontControl.frame = CGRectMake(-300, rect.origin.y, rect.size.width, rect.size.height);
    _isFont = NO;
    
     CGRect rect1 = self.noteBook.tableView.frame;
    self.noteBook.tableView.frame = CGRectMake(rect1.origin.x,700, rect1.size.width, rect1.size.height);
    _isBackgroundPic = NO;
       }
    }
      
    
    
}

#pragma mark - 键盘回收时触发的方法
- (void)keyboardDidHide
{
    
     self.noteBook.myTextView.inputAccessoryView.hidden = YES;
    
    if (!_isResponderForTape) {
       [self.noteBook myTextViewHeight:0];
    }
     
    
    // 当键盘回收的时候, 实行的方法
}

#pragma mark - 在界面即将消失的时候 注销监听
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
